package com.example.studentmanagement2.service.Impl;

import com.example.studentmanagement2.exception.StudentNotFoundException;
import com.example.studentmanagement2.exception.TeacherNotFoundException;
import com.example.studentmanagement2.model.Student;
import com.example.studentmanagement2.model.Teacher;
import com.example.studentmanagement2.repository.Repository.StudentRepository;
import com.example.studentmanagement2.repository.Repository.TeacherRepository;
import com.example.studentmanagement2.service.StudentService;
import com.example.studentmanagement2.service.TeacherService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class TeacherServiceImpl implements TeacherService {



    private final TeacherRepository teacherRepository;

    public TeacherServiceImpl(TeacherRepository teacherRepository) {
        this.teacherRepository = teacherRepository;
    }

    @Override
    public List<Teacher> getAllTeachers() {
        return teacherRepository.findAll();
    }

    @Override
    public Optional<Teacher> getTeacherById(String id) {
        return Optional.ofNullable(teacherRepository.findById(id)
                .orElseThrow(() -> new TeacherNotFoundException("Teacher not found with id: " + id)));
    }

    @Override
    public Teacher addTeacher(Teacher teacher) {
        if (teacherRepository.existsById(teacher.getId())) {
            throw new IllegalArgumentException("学号已存在！");
        }
        return teacherRepository.save(teacher);
    }

    // StudentServiceImpl.java
    @Override
    @Transactional
    public Teacher updateTeacher(String originalId, Teacher teacher) {
        // 检查原始学号是否存在
        if (!teacherRepository.existsById(originalId)) {
            throw new TeacherNotFoundException("原始学号不存在");
        }


        // 更新时传入原始学号
        teacherRepository.update(teacher, originalId);
        return teacher;
    }
    @Override
    public List<Teacher> searchTeachers(String keyword) {
        return teacherRepository.search(keyword);
    }



    @Override
    public void deleteTeacher(String id) {
        teacherRepository.deleteById(id);
    }
}